//
//  RequestPlugin.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2020/8/11.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import Foundation
import Moya
import Toast_Swift

/// 自定义插件
public final class SYNetworkLoadingPlugin: PluginType {
    
    public func willSend(_ request: RequestType, target: TargetType) {
        
    }
    
    public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
        
    }
}

struct SYAuthPlugin: PluginType {
    let token: String
    
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        var request = request
        request.timeoutInterval = 30
        request.addValue(token, forHTTPHeaderField: "token")
        request.addValue("ios", forHTTPHeaderField: "platform")
        request.addValue("version", forHTTPHeaderField: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String)
        return request
    }
}

final class SYRequestAlertPlugin: PluginType {
    
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        return request
    }
    
    func willSend(_ request: RequestType, target: TargetType) {
        //实现发送请求前需要做的事情
    }
    
    public func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        
        //        switch result {
        //        case .success(let response):
        //            guard response.statusCode == 200 else {
        //                if response.statusCode == 401 {
        //                    if isJumpLogin == false {
        //                        cancelAllRequest()
        //                        // 退出登录
        //                        if let nvc = (WTNavigationManger.Nav as? WTMainViewController) {
        //                            nvc.login()
        //                        }
        //                    }
        //                }
        //                return
        //            }
        //            var json = try? JSON(data: response.data)
        //            WTDLog("请求状态码\(json?["status"] ?? "")")
        //
        //            guard let codeString = json?["status"] else {return}
        //             if codeString == 401 {// 退出登录
        //                if isJumpLogin == false {
        //                    cancelAllRequest()
        //                    if let nvc = (WTNavigationManger.Nav as? WTMainViewController) {
        //                        nvc.login()
        //                    }
        //                }
        //                break
        //            }
        //
        //        case .failure(let error):
        //            WTDLog(error)
        //            let myAppdelegate = UIApplication.shared.delegate as! AppDelegate
        //            myAppdelegate.listenNetwork()
        //            break
        //        }
    }
}
